#include <iostream>
#include "cpp-httplib/httplib.h"
#include "search.hpp"
#include <signal.h>
#include <unistd.h>

const std::string root_path = "./wwwroot";
const std::string input = "data/raw_html/text.txt";
const std::string nullfile = "/dev/null";

// 守护进程
void Daemon()
{
    // 1, 忽略信号
    signal(SIGCLD, SIG_IGN);
    signal(SIGPIPE, SIG_IGN);
    signal(SIGSTOP, SIG_IGN);

    // 2，将自己变为独立的进程
    if(fork() > 0)
    {
        // parent
        exit(0);
    }


    // 3，改变目录

    // 4，重定向 标准输入 输出 错误
    int fd1 = open(nullfile.c_str(), O_RDWR);
    if(fd1 > 0)
    {
        dup2(fd1, 0);
        dup2(fd1, 2);
    }
    int fd = open(log_path.c_str(), O_RDONLY | O_WRONLY | O_APPEND, 0660);
    if(fd < 0)
    {
        std::cout << "打开失败" << std::endl;
    }
    dup2(fd, 1);
}

int main()
{
    Daemon();
    
    ns_search::Searcher searcher;
    searcher.InitSearcher(input);

    httplib::Server svr;
    svr.set_base_dir(root_path);
    svr.Get("/s", [&searcher](const httplib::Request& req, httplib::Response& rsp)
                {
                    if(!req.has_param("word"))
                    {
                        rsp.set_content("必须要有搜索关键字", "text/plain:charset=utf-8");

                        return;
                    }

                    std::string word = req.get_param_value("word");
                    // std::cout << "正在搜索 " << word << " " << std::endl;
                    std::string tmp = "正在搜索 " + word; 
                    LOG(INFO, tmp.c_str());

                    std::string json_string;
                    searcher.search(word, json_string);

                    rsp.set_content(json_string, "application/json");

                    tmp += " 搜索完毕";
                    LOG(INFO, tmp.c_str());
                });
    
    svr.listen("0.0.0.0", 8080);

    return 0;
}